package com.dashan.servlets;

import static com.dashan.Constants.AVAILABLE;
import static com.dashan.Constants.NOT_AVAILABLE;
import static com.dashan.Constants.USERNAME;
import static com.dashan.servlets.Parameter.Option.Required;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dashan.backend.datastore.UserDao;

@SuppressWarnings("serial")
public class CheckUserNameServlet extends DashanServlet {

    @Override
    public ArrayList<Parameter> getParameterList() {
        ArrayList<Parameter> res = super.getParameterList();
        res.add(new Parameter(USERNAME, Required, String.class));
        return res;
    }

    @Override
    public String getUrlPattern() {
        return "/checkusername";
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        TreeMap<String, Parameter> params = loadParamters(req);
        UserDao dao = new UserDao();
        try {
            boolean res = dao.isUserExist(params.get(USERNAME).stringValue());
            if (res) {
                resp.getWriter().print(NOT_AVAILABLE);
            } else {
                resp.getWriter().print(AVAILABLE);
            }
        } finally {
            dao.commit();
        }
    }

}
